#!/bin/bash

# start_controller.sh - Simple controller management script

CONTROLLER_PORT=${1:-10000}
CONTROLLER_SCRIPT="mock_controller.py"
PID_FILE=".controller.pid"
LOG_FILE=".controller.log"

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'

log() {
    echo -e "${GREEN}[$(date +'%H:%M:%S')]${NC} $1"
}

error() {
    echo -e "${RED}[$(date +'%H:%M:%S')] ERROR${NC} $1"
}

warn() {
    echo -e "${YELLOW}[$(date +'%H:%M:%S')] WARN${NC} $1"
}

check_port() {
    if lsof -Pi :$1 -sTCP:LISTEN -t >/dev/null; then
        return 0
    else
        return 1
    fi
}

start_controller() {
    if check_port $CONTROLLER_PORT; then
        warn "Port $CONTROLLER_PORT is already in use"
        return 1
    fi
    
    if [ ! -f "$CONTROLLER_SCRIPT" ]; then
        error "Controller script not found: $CONTROLLER_SCRIPT"
        return 1
    fi
    
    log "Starting Controller Mock Server on port $CONTROLLER_PORT..."
    python $CONTROLLER_SCRIPT $CONTROLLER_PORT > $LOG_FILE 2>&1 &
    echo $! > $PID_FILE
    
    # Wait for startup
    sleep 2
    
    if check_port $CONTROLLER_PORT; then
        log "Controller started successfully (PID: $(cat $PID_FILE))"
        log "Logs: $LOG_FILE"
        return 0
    else
        error "Failed to start controller"
        rm -f $PID_FILE
        return 1
    fi
}

stop_controller() {
    if [ -f "$PID_FILE" ]; then
        local pid=$(cat $PID_FILE)
        if ps -p $pid > /dev/null; then
            log "Stopping Controller (PID: $pid)..."
            kill $pid
            wait $pid 2>/dev/null || true
            log "Controller stopped"
        else
            warn "Controller was not running"
        fi
        rm -f $PID_FILE
    else
        warn "No PID file found"
    fi
}

restart_controller() {
    stop_controller
    sleep 1
    start_controller
}

status_controller() {
    if check_port $CONTROLLER_PORT; then
        log "Controller is RUNNING on port $CONTROLLER_PORT"
        if [ -f "$PID_FILE" ]; then
            log "PID: $(cat $PID_FILE)"
        fi
        return 0
    else
        log "Controller is STOPPED"
        return 1
    fi
}

test_controller() {
    log "Testing Controller..."
    
    # Test normal request
    if curl -s http://localhost:$CONTROLLER_PORT/health > /dev/null; then
        log "Health check: OK"
    else
        error "Health check: FAILED"
        return 1
    fi
    
    # Test normal alarm report
    response=$(curl -s -X POST http://localhost:$CONTROLLER_PORT/controller/report_alarm \
        -H "Content-Type: application/json" \
        -d '{"alarm_type":"test","message":"test message","severity":"warning"}')
    
    if echo "$response" | grep -q "success"; then
        log "Normal alarm report: OK"
    else
        error "Normal alarm report: FAILED"
        return 1
    fi
    
    # Test timeout alarm report (should timeout after 5s)
    log "Testing timeout scenario (this will take 5 seconds)..."
    if curl -s --max-time 5 -X POST "http://localhost:$CONTROLLER_PORT/controller/report_alarm?timeout=true" \
        -H "Content-Type: application/json" \
        -d '{"alarm_type":"test","message":"test timeout","severity":"warning"}' > /dev/null; then
        warn "Timeout test: Expected timeout but request succeeded"
    else
        log "Timeout test: OK (request timed out as expected)"
    fi
    
    log "Controller test completed"
}

show_usage() {
    echo "Usage: $0 {start|stop|restart|status|test|help} [port]"
    echo ""
    echo "Commands:"
    echo "  start   - Start controller (default port: 10000)"
    echo "  stop    - Stop controller"
    echo "  restart - Restart controller" 
    echo "  status  - Check controller status"
    echo "  test    - Test controller functionality"
    echo "  help    - Show this help"
    echo ""
    echo "Examples:"
    echo "  $0 start           # Start on port 10000"
    echo "  $0 start 11000     # Start on port 11000"
    echo "  $0 test            # Test controller"
}

# Handle port argument
if [ -n "$2" ]; then
    CONTROLLER_PORT="$2"
fi

case "$1" in
    start)
        start_controller
        ;;
    stop)
        stop_controller
        ;;
    restart)
        restart_controller
        ;;
    status)
        status_controller
        ;;
    test)
        status_controller && test_controller
        ;;
    help|--help|-h)
        show_usage
        ;;
    *)
        show_usage
        exit 1
        ;;
esac